package com.bos.util;

import com.bos.data.model.AccessTokenModel;
import com.bos.data.model.weixin.Menu;
import com.bos.service.AccessTokenService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class WeiXinUtil {
    // 此类封装了http请求、https请求、获取accessToken的方法
    private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
    // 微信的请求url
    // 获取access_token的接口地址（GET） 限200（次/天）
    public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";
    //通过accessToken和openid获得用户信息
    private final static String getAccess_token_open_id_url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    /**
     * 30 * 1.发起https请求并获取结果 31 * 32 * @param requestUrl 请求地址 33 * @param
     * requestMethod 请求方式（GET、POST） 34 * @param outputStr 提交的数据 35 * @return
     * JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 36
     */
    public static JSONObject httpRequest(String requestUrl,
                                         String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        }
        return jsonObject;
    }

    /**
     * 94 * 2.发起http请求获取返回结果 95 * 96 * @param requestUrl 请求地址 97 * @return 98
     */
    public static String httpRequest(String requestUrl) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url
                    .openConnection();

            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

        } catch (Exception e) {
        }
        return buffer.toString();
    }

    /**
     * 135 * 3.获取access_token 136 * 137 * @param appid 凭证 138 * @param appsecret
     * 密钥 139 * @return 140
     */
    public static AccessTokenModel getAccessToken(String appid, String appsecret, String type) {
        AccessTokenModel accessToken = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String saveDate = sdf.format(new Date());
        String requestUrl = access_token_url.replace("{corpId}", appid)
                .replace("{corpsecret}", appsecret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessTokenModel();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                accessToken.setType(type);
                accessToken.setSaveDate(saveDate);
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}",
                        jsonObject.getInt("errcode"),
                        jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    public static String getAccessToken(AccessTokenService accService, String type, String corpId, String secret) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<AccessTokenModel> access = accService.findAccessToken(type);
            // 如果没有AccessToken的话
            AccessTokenModel accessToken = null;
            if (access.size() <= 0) {
                // 首先要查询到accessToken(第一次查询的话，将accessToken保存到数据库中)
                accessToken = WeiXinUtil.getAccessToken(corpId, secret, type);
                System.out.println("accessToken:" + accessToken.getToken());
                int row = accService.insertAccessToken(accessToken);
                if (row > 0) {
                    System.out.println("增加成功");
                }
                return accessToken.getToken();
            } else {
                accessToken = access.get(0);
                String saveTime = accessToken.getSaveDate();
                long time = sdf.parse(saveTime).getTime();
                long now = new Date().getTime();
                long interval = (now - time) / 1000;
                if (interval > 7000) {// 超过7000秒，重新获取accessToken
                    accessToken = WeiXinUtil.getAccessToken(
                            QiWeiXinParamesUtil.corpId,
                            QiWeiXinParamesUtil.agentSecret, type);
                    // 更新数据库
                    String newDate = sdf.format(new Date());
                    accessToken.setSaveDate(newDate);
                    accessToken.setToken(accessToken.getToken());
                    accessToken.setExpiresIn(Integer.parseInt(String
                            .valueOf(interval)));
                    accessToken.setType(type);
                    int row1 = accService.updateByExpirIn(accessToken);
                    if (row1 > 0) {
                        System.out.println("----111---"
                                + accessToken.getToken());
                        System.out.println("更新成功");
                    }
                }

                return accessToken.getToken();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //4.自定义菜单的创建方法
    // 菜单创建（POST） 限100（次/天）
    public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    /**
     * 创建菜单
     *
     * @param menu 菜单实例
     * @param accessToken 有效的access_token
     * @return 0表示成功，其他值表示失败
     */
    public static int createMenu(Menu menu, String accessToken) {
        int result = 0;

        // 拼装创建菜单的url
        String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
        // 将菜单对象转换成json字符串
        String jsonMenu = JSONObject.fromObject(menu).toString();
        // 调用接口创建菜单
        JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);

        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }

        return result;
    }
    // 获取access_token的接口地址（GET） 限200（次/天）
    public final static String access_token_url2 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取access_token
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessTokenModel getAccessToken2(String appid, String appsecret) {
        AccessTokenModel accessToken = null;

        String requestUrl = access_token_url2.replace("APPID", appid).replace("APPSECRET", appsecret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessTokenModel();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

   /* public static BosCustomerModel getUserInfoByAccessTokenAndOpenId(String accessToken, String openId) {
        //String requesUrl = getAccess_token_open_id_url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
       // JSONObject jsonObject = httpRequest(requesUrl, "GET", null);
        BosCustomerModel model = new BosCustomerModel();
        //if (jsonObject != null) {
            try {
                model.setCname("");
                model.setOpenId(openId);
            } catch (Exception e) {
                log.error("获取用户信息失败 accessToken:{},openId:{}", accessToken, openId);
                return null;
            }
       // }
        return model;
    }
*/
}
